Default parameters


Default parameters intruduced as a
new feature of Dephi 4. Like C++ default parameters
now you can assign default value for procedure or function parameters such as:

procedure DoSomeThing(X: byte; Y: byte = 1);

This declaration means that you can call above procedure by one parameter or by
two parameters such as:

DoSomeThing(3, 5);
DoSomeThing(6);

At first calling value 3 will be passed to X variable, and 5 to Y, but at second
calling 6 will be passed to X but nothing passed to Y, so that the default ( 1 )
value of Y will be used.

Example:

function Sum(a1: integer; a2: integer = 0; a3: integer = 0): integer;
begin
Result:= a1 + a2 + a3;
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(
Sum(4)));
ShowMessage(IntToStr(
Sum(5, 3)));
ShowMessage(IntToStr(
Sum(1, 2, 3)));
end;

Note:

Default parameters must declared from right to left not from left to right:

procedure A(X: byte; Y: byte = 3; Name: string = '');

But below example is an invalid declaration:

procedure A(X: byte = 4; Y: byte = 3; Name: string);

Also in calling you must ignor parameters from right to left such as:

X:= Sum(1, 2, 3);
Y:= Sum(1, 2);
Z:= Sum(1);

But below examples are incorrect:

X:= Sum( , 2, 3);
Y:= Sum( , , 3);
Z:= Sum(1, , 3);


See also:

Procedure and function overloading